package com.secneo.appshare.activities;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.webkit.WebView;

import com.kaixin.connect.Kaixin;
import com.kaixin.connect.Util;
import com.secneo.appshare.AppShareApplication;
import com.secneo.appshare.R;
import com.secneo.appshare.api.LocalStore;
import com.secneo.appshare.api.RemoteApi.Feed;
import com.secneo.appshare.api.RemoteApi.UserInfo;
import com.secneo.appshare.api.impl.RemoteApiImpl;
import com.secneo.appshare.common.ActivityUtil;
import com.secneo.appshare.common.Constants;

public class KaixinLoginFinishActivity extends CommonActivity
{
	public static boolean mRecyleFlag = false;

	private ProgressDialog mProgressDialog = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.kaixin_login);
		AppShareApplication.getInstance().addActivity(this);

		mProgressDialog = new ProgressDialog(KaixinLoginFinishActivity.this);
		mProgressDialog.setMessage("加载中，请稍候...");
		mProgressDialog.setCancelable(false);
		mProgressDialog.show();

		Kaixin kaixin = Kaixin.getInstance();

		Uri uri = getIntent().getData();
		if (uri != null) {
			Bundle bund = Util.decodeUrl(uri.toString());
			String verifier = (String) bund.get("oauth_verifier");
			try {
				if (verifier != null) {
					// 获取Access Token
					if (kaixin.getAccessToken(this, kaixin.getRequestToken(),
							kaixin.getRequestTokenSecret(), verifier)) {
						// 存储Access Token
						kaixin.updateStorage(this);

						processPostLoginEvent();
					}
				}

			} catch (Exception e) {
				Log.e("MyTag", e.toString());
			}
		}
		
	}
	

	private Handler mKaixinLoginHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch(msg.what) 
			{
			case Constants.MSG_KAIXIN_LOGIN_SUCCESS:
				Activity activity = LocalStore.getLocaleStoreInstance().getStoredActivity();
				activity.finish();
				finish();
				break;

			case Constants.MSG_KAIXIN_LOGIN_FAILED:
				finish();
				break;
			}
			super.handleMessage(msg);
		}
	};
	

	public void processPostLoginEvent()
	{
		Thread kaixinLoginThread = new Thread() 
		{
			public void run()
			{
				try 
				{
					LocalStore.getLocaleStoreInstance().setKaixinAccountActive();
					LocalStore.getLocaleStoreInstance().getKaixinUserInfo();
					
					RemoteApiImpl remoteApi = new RemoteApiImpl();
					UserInfo ret = null;
					String localName = LocalStore.getLocaleStoreInstance().getNickName();
					String localIcon = LocalStore.getLocaleStoreInstance().getAvatarName();
					
					boolean first_login = (LocalStore.getLocaleStoreInstance().getAndroidId() == null ||
							LocalStore.getLocaleStoreInstance().getAndroidId() == "") ? true : false ;
					
					if(localName.equals("")){
						localName = LocalStore.getLocaleStoreInstance().getKaixinUserNameString();
						localIcon = LocalStore.getLocaleStoreInstance().getKaixinPicUrlString();
					}
					
					ret = remoteApi.addNewWeiboUser(KaixinLoginFinishActivity.this, 3, 
							LocalStore.getLocaleStoreInstance().getKaixinUidString(), 
							localName, localIcon);
					
					if (ret == null){ 
						Log.d("MyTag", "Register kaixin user failed!");
						Message msg = new Message();
						msg.what = Constants.MSG_KAIXIN_LOGIN_FAILED;
						mKaixinLoginHandler.sendMessage(msg);
						return;
					}
					else
					{
						if(ret.id.equals(Constants.SNS_HAS_ASSOCIATE) || 
								ret.id == Constants.SNS_HAS_ASSOCIATE){
							String nickName = LocalStore.getLocaleStoreInstance().getKaixinUserNameString();
							String tmp = "安卓号 "+nickName + " 已被绑定过，只能销毁原账号才能进行绑定操作。详见帮助。" ;
							ActivityUtil.alert(KaixinLoginFinishActivity.this, tmp);
							Message msg = new Message();
							msg.what = Constants.MSG_KAIXIN_LOGIN_FAILED;
							mKaixinLoginHandler.sendMessage(msg);
							return;
						}
						
						if(ret.id != null && !"".equals(ret.id)){
							LocalStore.getLocaleStoreInstance().setUid(ret.id);
							LocalStore.getLocaleStoreInstance().setAndroidId(ret.androidId);
						}
						LocalStore.getLocaleStoreInstance().storeKaixinAccountInfoToLocal();

						LocalStore.getLocaleStoreInstance().setNickName(ret.nick);
						LocalStore.getLocaleStoreInstance().setAvatarName(localIcon);
					}
					

		    		Intent intentw = new Intent();
		    		if(first_login){
						Bundle mBundle = new Bundle(); 
						mBundle.putInt("sns_type", Constants.SNS_INDEX_KAIXIN);
						intentw.putExtras(mBundle);
		    			intentw.setClass(KaixinLoginFinishActivity.this, UserInfoActivity.class);
						startActivity(intentw);
		    		}
		    		else {
						Bundle mBundle = new Bundle(); 
						mBundle.putInt("sns_type", Constants.SNS_INDEX_KAIXIN);
						intentw.putExtras(mBundle);
		    			intentw.setClass(KaixinLoginFinishActivity.this, ChooseUserActivity.class);
						startActivity(intentw);
		    		}
			    	
		    		
					Bitmap bmp = BitmapFactory.decodeResource(KaixinLoginFinishActivity.this.getResources(), R.drawable.icon);
			        ByteArrayOutputStream baos = new ByteArrayOutputStream();
			        bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
			        byte[] content = baos.toByteArray();
					ActivityUtil.shareToWeibo(KaixinLoginFinishActivity.this, Constants.UPLOAD_ACTION_LOGIN, null, null, content, null, 
							Constants.SERVER_BANGSHARE_ICON_URL, null, null);
					bmp.recycle();bmp = null;
					Message msg = new Message();
					msg.what = Constants.MSG_KAIXIN_LOGIN_SUCCESS;
					mKaixinLoginHandler.sendMessage(msg);
					return;
				}
				catch (Exception ex) {
					Log.d("MyTag", "Exception: "+ex.getMessage());
					LocalStore.getLocaleStoreInstance().logoutKaixinAccount();
					Message msg = new Message();
					msg.what = Constants.MSG_KAIXIN_LOGIN_FAILED;
					mKaixinLoginHandler.sendMessage(msg);
					return;
				}
			}
		};
		kaixinLoginThread.start();
		
		
	}

}